<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8" />
  <title>Cesium 真实地形小车动画示例</title>
  <script src="https://cesium.com/downloads/cesiumjs/releases/1.115/Build/Cesium/Cesium.js"></script>
  <link href="https://cesium.com/downloads/cesiumjs/releases/1.115/Build/Cesium/Widgets/widgets.css" rel="stylesheet" />
  <style>
    html, body, #cesiumContainer {
      margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden;
    }
  </style>
</head>
<body>
<div id="cesiumContainer"></div>
<script>
  // 初始化Viewer，开启地形和卫星影像
  const viewer = new Cesium.Viewer('cesiumContainer', {
    terrainProvider: Cesium.createWorldTerrain(),
    imageryProvider: new Cesium.IonImageryProvider({ assetId: 2 }),
    baseLayerPicker: false
  });

  // 定义小车路线（经纬度，先无高度）
  const positions = [
    { longitude: 116.3913, latitude: 39.9075 },   // 北京天安门
    { longitude: 116.395, latitude: 39.910 },
    { longitude: 116.400, latitude: 39.912 },
    { longitude: 116.405, latitude: 39.915 }
  ];

  // 采样地形高度
  Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, positions).then(updatedPositions => {
    // 定义时间范围，1分钟内完成动画
    const start = Cesium.JulianDate.now();
    const stop = Cesium.JulianDate.addMinutes(start, 1, new Cesium.JulianDate());

    viewer.clock.startTime = start.clone();
    viewer.clock.stopTime = stop.clone();
    viewer.clock.currentTime = start.clone();
    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
    viewer.clock.multiplier = 1;

    // 创建动态位置属性
    const positionProperty = new Cesium.SampledPositionProperty();
    updatedPositions.forEach((pos, i) => {
      const time = Cesium.JulianDate.addSeconds(start, i * 20, new Cesium.JulianDate());
      const cartesian = Cesium.Cartesian3.fromDegrees(pos.longitude, pos.latitude, pos.height);
      positionProperty.addSample(time, cartesian);
    });

    // 自动计算朝向
    const orientationProperty = new Cesium.VelocityOrientationProperty(positionProperty);

    // 添加小车模型实体
    const entity = viewer.entities.add({
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({ start: start, stop: stop })
      ]),
      position: positionProperty,
      orientation: orientationProperty,
      model: {
        uri: "https://cesium.com/downloads/cesiumjs/releases/1.115/Apps/SampleData/models/CesiumGroundVehicle/Cesium_GroundVehicle.glb",
        minimumPixelSize: 64,
        maximumScale: 200
      },
      path: {
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.CYAN
        }),
        width: 10
      }
    });

    // 视角跟随小车
    viewer.trackedEntity = entity;
  });
</script>
</body>
</html>
